
import {Injectable} from "@angular/core";
import {Headers, Response} from "@angular/http";
import "rxjs/add/operator/toPromise";
import {UPLOAD_DOMAIN} from '../../constant/config';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CacheService } from '@core/routes-services/cache.service';
/**
 * 上传下载服务工具
 */
@Injectable()
export class UploadFileUtilService {
  private http: HttpClient;
  cacheService: CacheService;
  constructor(http: HttpClient,cacheService: CacheService) {
    this.http = http;
    this.cacheService = cacheService;
  }

  uploadDomain=UPLOAD_DOMAIN;


  /**
   * 上传文件
   *
   * @param {File} file
   * @returns {Promise<any>}
   */
  uploadFile(file:File,type?:any): Promise<any> {
    let formData = new FormData();
    formData.append("file", file);
    let url = this.uploadDomain;
    return this.http.post(url, formData,getRequestHeader(this.cacheService))
      .toPromise()
      .then((res: any) => {
        if (res.ok) {
          return res.body || {};
        } else {// 结合后台返回数据格式 正常不应该到这里
          return res;
        }
    })
      .catch(this.handleError)
  }
  private handleError(error: Response | any) {
    console.log("上传=error============")
    let ua = navigator.userAgent.toLowerCase();
    let isWeixin = ua.indexOf("micromessenger") >= 0;
    if (error.status == 403 || (error.status == 419 && isWeixin)) {
      // window.location.href = "#/forbidden"
      // return Promise.resolve("Sorry,You don't have permission.");
    }
    if (error.status == 401 && !isWeixin) {
      //未登录，先登录
      window.location.href = "#/login";
      //return Promise.resolve("Please sweep the qr code.");
    }
    // let errMsg = (error.message) ? error.message :
    //   error.status ? `${error.status} - ${error.statusText}` : 'Server error'
    return Promise.reject(error);
  }
}
export function getRequestHeader(cacheService:CacheService): any {
    let headers = new HttpHeaders();
    headers.append('X-Requested-With', 'XMLHttpRequest');
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json; charset=UTF-8');
    const token: any = cacheService.getTokenInfo();
    if (token !== null) {
      headers = headers.append('Authorization',  token);
    }

    return { headers: headers, withCredentials: true, observe: 'response' };// observe: 'response' 定义返回整个response 而不仅仅是body ，各请求再根据后端返回结构做进一步处理
}
